<?php

class WebApplicationEndBehavior extends CBehavior {
    // Web application end's name.
    private $_endName;

    // Getter.
    // Allows to get the current -end's name
    // this way: Yii::app()->endName;
    public function getEndName () {
        return $this->_endName;
    }

    // Run application's end.
    public function runEnd ($name) {
        $this->_endName = $name;

        // Attach the changeModulePaths event handler
        // and raise it.
        $this->onModuleCreate = array($this, 'changeModulePaths');
        $this->onModuleCreate(new CEvent($this->owner));

        $this->configMailerComponent();
        $this->owner->run(); // Run application.
    }

    // This event should be raised when CWebApplication
    // or CWebModule instances are being initialized.
    public function onModuleCreate ($event) {
        $this->raiseEvent('onModuleCreate', $event);
    }

    // onModuleCreate event handler.
    // A sender must have controllerPath and viewPath properties.
    protected function changeModulePaths ($event) {
        $event->sender->controllerPath .= DIRECTORY_SEPARATOR . $this->_endName;
        $event->sender->viewPath .= DIRECTORY_SEPARATOR . $this->_endName;
    }

    private function configMailerComponent () {
        $smtp = Yii::app()->params['mailer'];
        Yii::app()->mailer->Host = $smtp['host'];
        Yii::app()->mailer->IsSMTP();
        Yii::app()->mailer->SMTPAuth = true;
        Yii::app()->mailer->From = $smtp['email'];
        Yii::app()->mailer->Port = $smtp['port'];
        Yii::app()->mailer->Username = $smtp['user'];
        Yii::app()->mailer->Password = $smtp['pass'];
        Yii::app()->mailer->FromName = $smtp['name'];
    }
}